import React, { useEffect, useState, useMemo, forwardRef, useImperativeHandle, useRef } from 'react'
import { InbizIcon } from '@inbiz/utils';
import { Select, Form, Input, Divider, Cascader, Space, } from 'antd'
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { TextWidget, getMessage } from '@inbiz/react';
import EformDateRangePicker from '@components/form/base/EformDateRangePicker/preview/web';
import EformMemberSelect from '@components/form/grade/EformMemberSelect/preview/web'
import BelongDirectory from '@inbiz/basic/BelongDirectory'
import { CustomInput } from '../../AdvancedSearch/controlTypeFormItem'
import { useSearchUIState } from '../../../../../store/hooks/useSearchUIState';
import { useConfigEventsApi, useSearchPropsState } from '../../../../../store/hooks/useSearchPropsState';
import { getMetaTypeList } from '../../../../../designer/service';
import {
  fileschemaOptions,
} from './utils';
import { getComponent, filterkeys } from '../../../../../searchCommon'
import useSecretlevel from '../../commonUtils/useSecretLevel'
import type { ConditionItemType } from './utils';
import './index.less'

const { Option } = Select
const getNewOptions = (options) => {
  return options.map(item => ({
    ...item,
    label: getMessage(item.label),
    value: item.key.toLowerCase(),
    ControlModel: {
      ControlType: item.controlType,
      Setting: [{
        id: 'datasource',
        value: JSON.stringify(item.options.map(ele => ({ ...ele, text: getMessage(ele.text) })))
      }, {
        id: 'mode',
        value: 'singleSelectbox',
      }]
    }
  }))
}

type metaDataItemType = ConditionItemType & { casValue: string[] }

export default forwardRef(function DocumentAdvancedSearch(props: any, ref) {
  const { form, onFinish, inbiz, fileTypeParams } = props
  const [casData, $casData] = useState<any>([])
  const [searchEngineData, $searchEngineData] = useState({})
  const addDataRef = useRef()
  const [metaDataItems, $metaDataItems] = useState<metaDataItemType[]>([])
  const newfileschemaOptions = useSecretlevel({ options: fileschemaOptions })
  const { selectShowTab, showTeam, showPerson } = useSearchUIState()
  const { fixedWidth, interactiveMethods } = useSearchPropsState()
  const { configEvents } = useConfigEventsApi();
  const initData = useMemo(() => {
    if (selectShowTab!.isFile) {
      return [{
        label: getMessage('SearchEngine.basicInfo'),
        value: 'basicInfo_1',
        children: getNewOptions(newfileschemaOptions)
      }]
    }
    return []
  }, [selectShowTab])

  const getmetatypelist = () => {
    getMetaTypeList().then(res => {
      if (selectShowTab!.isFile || selectShowTab!.isFolder) {
        $casData(initData)
      }
      if (res.isSucceed && !!res.result?.length) {
        const newData = res.result.map(item => {
          return {
            ...item,
            label: item.TypeName,
            value: item.TypeId,
            key: item.TypeId,
            children: item.MetaAttrList.filter(element => element.ControlModel.ControlType !== 'edoc2Hidden').map(ele => ({ ...ele, label: ele.AttrName, value: ele.AttrId, key: ele.AttrId }))
          }
        })
        if (selectShowTab!.isFile || selectShowTab!.isFolder) {
          $casData([...initData, ...newData])
        } else {
          $casData(newData)
        }
      }
    })
  }
  const initmetadataitems = () => {
    let initmetaitems = localStorage.getItem('_searchEngineStatus') || sessionStorage.getItem('_searchEngineStatus')
    localStorage.removeItem('_searchEngineStatus')
    if (initmetaitems) {
      sessionStorage.setItem('_searchEngineStatus', initmetaitems)
      // 要筛选默认的, 
      const parsedItems = JSON.parse(initmetaitems)
      $searchEngineData(parsedItems)
      const metaArray = selectShowTab!.isFile ? parsedItems.metaData?.file : parsedItems.metaData?.folder
      if (metaArray && metaArray.length > 0) {
        metaArray.forEach(element => {
          element.key = element.key
        });
        const defaultItems = metaArray.filter(item => {
          return filterkeys.includes(item.key)
        })
        const commonFileOrFolder = ['filename', 'foldername', 'filepath', 'folderpath']
        for (let index = 0; index < defaultItems.length; index++) {
          const element = defaultItems[index];
          if (commonFileOrFolder.includes(element.key)) {
            form.setFieldsValue({
              [element.key]: element
            })
          } else {
            form.setFieldsValue({
              [element.key]: element.value
            })
          }
        }
        const metaItems = metaArray.filter(item => {
          return !filterkeys.includes(item.key)
        })

        $metaDataItems(metaItems)
      }
    }
  }
  useEffect(() => {
    if (selectShowTab!.isFile || selectShowTab!.isFolder) {
      initmetadataitems()
    }
  }, [selectShowTab])
  useEffect(() => {
    getmetatypelist()
  }, [])
  useImperativeHandle(ref, () => {
    return {
      resetMetaFields: () => {
        $metaDataItems([])
      }
    }
  }, [])

  const getCasData = (casValue: string[]) => {
    if (casValue && casData.length > 0) {
      const parentItem = casData.find(ele => ele.value == casValue[0]) || {}
      const childItem = parentItem?.children.find(ele => ele.value == casValue[1]) || {}
      const { ControlType, Setting } = childItem.ControlModel
      const modeObj = Setting.find(ele => ele.id == 'mode')
      const optionsObj = Setting.find(ele => ele.id == 'datasource')
      const options = optionsObj?.value ? JSON.parse(optionsObj.value) : []
      return {
        ControlType, Setting, modeObj, options
      }
    }
    return {}
  }

  const displayRender = (labels: string[]) => labels[labels.length - 1];
  const addMetaDataItems = () => {

    $metaDataItems(list => {
      const newList = [...list]
      return [...newList, {
        key: '',
        type: '',
        label: '',
        controlType: '',
        controlId: '',
        options: [],
        mode: '',
        value: '',
      }]
    })
    setTimeout(() => {
      addDataRef?.current?.scrollIntoView({ behavior: "smooth" })
    }, 100)

  }
  const removeMetaDataItems = (index) => {
    $metaDataItems(list => {
      const newList = [...list]
      newList.splice(index, 1)
      return newList
    })
  }
  const changeCas = (val, index) => {
    const parentItem = casData.find(ele => ele.value == val[0]) || {}
    const childItem = parentItem?.children.find(ele => ele.value == val[1]) || {}
    const { ControlType, modeObj, options } = getCasData(val)
    const restItemObj = {
      controlType: ControlType,
      options,
      mode: modeObj?.value,
    }
    $metaDataItems(list => {
      const newList = [...list]
      newList[index] = { ...childItem, ...restItemObj, casValue: val, value: '' }

      return newList
    })
  }

  const directoryParams = {
    PageIndex: 1,
    PageSize: 10,
    IndexName: selectShowTab?.isFile ? "file" : 'folder',
    KeyWord: '*',
    SearchWhere: '',
    SearchFields: '',
    ExcludesFields: '',
    HighlightField: '',
    Sort: '',
    Order: 'desc',
    groupNum: '',
    ModuleName: '',
    PreTags: "<span style='color:var(--search-color)'>",
    PostTags: '</span>',
    IsFuzzySearch: true,
    FuzzyFields: '',
    Mark: '',
    SecondaryWord: '',
    IsSynonymSearch: false,
    categorySearchWhere: ''
  }
  const BelongDirectoryComponent = useMemo(() => {
    const pathkey = selectShowTab?.isFile ? "filepath" : 'folderpath'
    return <BelongDirectory
      params={directoryParams}
      configEvents={configEvents}
      topPersonalFolderId={inbiz.userInfo.topPersonalFolderId}
      pathkey={pathkey}
      showTeam={showTeam}
      showPerson={showPerson}
      config={{ resultsSearchCriteria: '' }}
      searchEngineData={searchEngineData}
      advancedSearch
    />
  }, [props, selectShowTab, showPerson, showTeam, searchEngineData])

  useEffect(() => {
    if (casData.length > 0) {

      const getTopKey = (key) => {
        const theCasData = casData.find(item => item.children.some(ele => ele.key == key || ele.value == key))
        if (theCasData?.value) {
          return [theCasData.value, key]
        }
      }
      metaDataItems.forEach((item, index) => {
        if (getTopKey(item.key)) {

          form.setFieldValue(`cascader_${index}`, getTopKey(item.key))
        }
      })
    }

  }, [metaDataItems, casData])

  const formItemWidth: number = useMemo(() => {
    if (fixedWidth && interactiveMethods == 'fixedWidth') {
      let formItemWidth: number = fixedWidth
      if (typeof fixedWidth == 'string') {
        const pIndex = fixedWidth.indexOf('p')
        formItemWidth = Number(fixedWidth.slice(0, pIndex))
      }
      return formItemWidth
    }
    return 430
  }, [fixedWidth])

  return (
    <div>
      <div className='advancedSearchTitle'>
        <TextWidget>SearchEngine.advancedSearch</TextWidget>
      </div>
      <Form
        labelCol={{ span: formItemWidth > 420 ? 3 : 4 }}
        wrapperCol={{ span: formItemWidth > 420 ? 21 : 20 }}
        form={form}
        colon={false}
        onFinish={onFinish}
        className={selectShowTab?.isFile ? 'fileForm' : 'forlderForm'}
        name='initForm'
      >
        {/**名称 */}
        <Form.Item
          label={getMessage('SearchEngine.advancedName')}
          name={selectShowTab?.isFile ? "filename" : 'foldername'}
          initialValue={{
            key: selectShowTab?.isFile ? "filename" : 'foldername',
            type: '',
            label: '',
            controlType: '',
            controlId: '',
            options: [],
            mode: '',
            value: '',
          }}
        >
          <CustomInput />
        </Form.Item>
        {/**所在目录 */}
        <Form.Item
          label={getMessage('SearchEngine.belongCategory')}
          name={selectShowTab?.isFile ? "filepath" : 'folderpath'}
          initialValue={{
            key: selectShowTab?.isFile ? "filepath" : 'folderpath',
            type: '',
            label: '',
            controlType: '',
            controlId: '',
            options: [],
            mode: '',
            value: '',
          }}
        >
          {BelongDirectoryComponent}
        </Form.Item>
        {/**文件类型 */}
        {selectShowTab?.isFile && <Form.Item
          label={getMessage('SearchEngine.fileType')}
          name="fileextname"
        >
          <Select placeholder={getMessage('SearchEngine.pleaseInput')} options={fileTypeParams} getPopupContainer={() => document.body} dropdownClassName='selectFileType'>
          </Select>
        </Form.Item>}
        <Form.Item style={{ marginBottom: 0 }} wrapperCol={{ span: 24 }} label={getMessage('SearchEngine.createInfo')}>
          <Form.Item
            style={{ display: 'inline-block', width: 'calc(50% - 80px)' }}
            name={`${selectShowTab?.isFile ? 'filecreateoperator' : 'foldercreateoperator'}`}
          >
            <EformMemberSelect
              inbiz={inbiz}
              multiple={false}
              tabs={['user']}
            />
          </Form.Item>
          <Form.Item
            style={{ display: 'inline-block', width: 'calc(50% + 72px)', margin: '0 0 0 8px' }}
            name={`${selectShowTab?.isFile ? 'filecreatetime' : 'foldercreatetime'}`}
          >
            <EformDateRangePicker
              dateQuickChoose
              style={{ width: '100%' }}
              inbiz={inbiz}
              format='YYYY-MM-DD'
              positionTop={-24}
              startPlaceholder='SearchEngine.pleaseInput'
              endPlaceholder='SearchEngine.pleaseInput'
            />
          </Form.Item>
        </Form.Item>
        <Form.Item style={{ marginBottom: 0 }} wrapperCol={{ span: 24 }} label={getMessage('SearchEngine.modifyInfo')}>
          <Form.Item
            style={{ display: 'inline-block', width: 'calc(50% - 80px)' }}
            name={`${selectShowTab?.isFile ? 'filemodifyoperator' : 'foldermodifyoperator'}`}
          >
            <EformMemberSelect
              inbiz={inbiz}
              multiple={false}
              tabs={['user']}
            />
          </Form.Item>
          <Form.Item
            style={{ display: 'inline-block', width: 'calc(50% + 72px)', margin: '0 0 0 8px' }}
            name={`${selectShowTab?.isFile ? 'filemodifytime' : 'foldermodifytime'}`}
          >
            <EformDateRangePicker
              dateQuickChoose
              style={{ width: '100%' }}
              inbiz={inbiz}
              format='YYYY-MM-DD'
              positionTop={-24}
              startPlaceholder='SearchEngine.pleaseInput'
              endPlaceholder='SearchEngine.pleaseInput'
            />

          </Form.Item>
        </Form.Item>
        <Divider />
        {
          metaDataItems.map((item, index) => {
            return <Space key={index} style={{ display: 'flex', marginBottom: 0, alignItems: 'center' }} align="baseline">
              <Form.Item
                style={{ width: 16, display: 'inline-block', }}
              >
                <MinusCircleOutlined style={{ color: '#aaa' }} onClick={() => removeMetaDataItems(index)} />
              </Form.Item>
              <Form.Item
                style={{ width: 150, display: 'inline-block', }}
                wrapperCol={{ span: 24 }}
                name={`cascader_${index}`}
                initialValue={item.casValue}
              >
                <Cascader
                  displayRender={displayRender}
                  dropdownClassName="metaDataField"
                  placeholder={getMessage('SearchEngine.selectField')}
                  options={casData}
                  onChange={(val) => changeCas(val, index)}
                  getPopupContainer={() => document.body}
                // open
                />
              </Form.Item>
              <Form.Item
                style={{ width: interactiveMethods == 'fixedWidth' ? formItemWidth - 221 : 381, marginLeft: 7, display: 'inline-block', marginBottom: 0 }}
                wrapperCol={{ span: 24 }}
                dependencies={[`cascader_${index}`]}
              >
                {
                  () => {
                    return <Form.Item initialValue={item} name={item.key}>
                      {getComponent(item)}
                    </Form.Item>
                  }
                }
              </Form.Item>
            </Space>
          })
        }
        <div ref={addDataRef} className='addCondition'>
          <div style={{ cursor: 'pointer' }} onClick={addMetaDataItems}><InbizIcon type='icon-ic-xinzeng' style={{ fontSize: 16, marginRight: 10 }} />\
            <div style={{ cursor: 'pointer' }} onClick={addMetaDataItems}><InbizIcon type='icon-ic-xinzeng' style={{ fontSize: 16, marginRight: 10 }} />
              <TextWidget>SearchEngineView.addCondition</TextWidget>
            </div>
          </div>
        </div>
      </Form>
    </div>
  )
})
